package com.xiaoyu.cloudmusic.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class AddressInvertUtil {
    public static String InvertLocalhostToIp() throws SocketException {
        Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
        while (nifs.hasMoreElements()) {
            NetworkInterface nif = nifs.nextElement();

            // 获得与该网络接口绑定的 IP 地址，一般只有一个
            Enumeration<InetAddress> addresses = nif.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();

                if (addr instanceof Inet4Address) { // 只关心 IPv4 地址
                    if(nif.getName().equals("wlan2")){
                        return addr.getHostAddress();
                    }
                }
            }

        }
        return "";
    }
    public static String localHostReplace(String oldStr) throws SocketException {
        if(oldStr != null){
            return oldStr.replace("localhost",InvertLocalhostToIp());
        }else return "";
    }
}
